#########################################################################################
# Package       Wx::Perl::SimpleThread::Thread
# Description:  Base for threads
# Created       Mon Mar 29 15:33:13 2010
# SVN Id        $Id: Thread.pm 5 2010-03-30 09:55:07Z mark.dootson $
# Copyright:    Copyright (c) 2010 Mark Dootson
# Licence:      This program is free software; you can redistribute it 
#               and/or modify it under the same terms as Perl itself
#########################################################################################

package Wx::Perl::SimpleThread::Thread;

#########################################################################################

use strict;
use warnings;
require Exporter;
use base qw( Exporter );
use threads;
use threads::shared;
use Time::HiRes qw( sleep );

our $VERSION = '0.02';

our @EXPORT = ();
our @EXPORT_OK = qw ( queue_event exit_thread );
our %EXPORT_TAGS = ( all => \@EXPORT_OK, everything => \@EXPORT_OK );

our $_wxpst_input_queue;
our $_wxpst_output_queue;
our $_wxpst_thread_continue = 1;

sub _set_wxpst_input_queue     { $_wxpst_input_queue  = $_[1]; }
sub _set_wxpst_output_queue    { $_wxpst_output_queue  = $_[1]; }
sub _set_wxpst_thread_continue { $_wxpst_thread_continue = $_[1]; }

sub _wxpst_handle_input_queue {
    my $class = shift;
    
    while($_wxpst_thread_continue) {
        my $sleepfor = 0.10;
        if( defined(my $params = $_wxpst_input_queue->dequeue_nb )) {
            my $firstevent = { '_wxpst_return_type' => 'started' };
            $class->queue_data( $firstevent );
            my $result = $class->do_request( $params );
            my $secondevent = { '_wxpst_return_type' => 'finished', '_wxpst_return_data' => $result };
            $class->queue_data( $secondevent );
        }
        sleep $sleepfor;
    }
    $class->exit_thread;
}

sub queue_data { $_wxpst_output_queue->enqueue( $_[1] ); }

sub exit_thread {
    my $class = shift;
    my $exitevent = { '_wxpst_return_type' => 'exit' };
    $class->queue_data( $exitevent );
    threads->exit;
}

sub do_request {
    my ($class, $paramref) = @_;
    my ($package, $filename, $line) = caller;
    die q(You must override ' . $package . '->do_request' in a derived package);
}

1;
